package cn.rokhdelar.umbrsapi.management.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.time.LocalDate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 管理人员实体，后台管理系统登录即查询本实体
 */
@Entity
@Data
public class SysUser implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    //  登录用户名，建议采用手机号
    private String username;
    //  登录密码，加密后的密码
    @JsonIgnore
    private String password;
    //  姓名
    @JoinColumn(unique = true)
    private String name;
    //  激活状态
    private Boolean active = true;
    //  所属部门
    @ManyToOne
    @JoinColumn
    private SysDepartment sysDepartment;
    //  性别
    private Boolean gender;
    //  职务/岗位
    private String position;
    //  联系电话
    private String phone;
    //  邮件地址
    private String email;
    //  创建时间
    private LocalDate createdDateTime;
    //  密码是否过期
    private Boolean passwordExpired = true;
    //  备注
    private String remark;
    //  角色列表
    @ManyToMany(fetch = FetchType.EAGER, cascade = {})
    @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT),
            inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
//    @JsonIgnore
    private Set<SysRole> sysRoles;

    @PrePersist
    private void prePersist() {
        this.createdDateTime = LocalDate.now();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        Set<SysRole> roles = this.getSysRoles();
        for (SysRole role: roles) {
            Set<SysPermission> authoritySet = role.getSysPermissions();
            for (SysPermission authority : authoritySet) {
                String permission = authority.getPermission();
                if (StringUtils.isNotEmpty(permission)) {
                    authorities.add(new SimpleGrantedAuthority(permission));
                }else {
                    throw new UsernameNotFoundException("用户权限错误。");
                }
            }
        }
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
